import 'dart:async';



import 'package:dio/dio.dart';

import 'package:flutter/material.dart';

import 'package:flutter_markdown/flutter_markdown.dart'; // <--- 导入 flutter_markdown

import 'package:markdown/markdown.dart' as md; // 导入 markdown 库用于解析



import '../../api/post_api.dart';

import '../../models/response.dart';

import '../../models/post.dart';

import '../../models/community.dart';



import '../api/collect.dart';

import 'comment/comment_widget.dart';



class PostDetailScreen extends StatefulWidget {

  final String postId;



  const PostDetailScreen({

    super.key,

    required this.postId,

  });



  @override

  State<PostDetailScreen> createState() => _PostDetailScreenState();

}



class _PostDetailScreenState extends State<PostDetailScreen> {

  final PostApi _postApi = PostApi();

  final CollectAPI _collectApi = CollectAPI();

  Post? _post;

  bool _isLoading = true;

  String? _errorMessage;

  bool _isLiked = false;

  bool _isCollected = false;



  @override

  void initState() {

    super.initState();

    _fetchPostDetailAndInteractionStatus();

  }



  /// 获取帖子详情、点赞和收藏状态

  Future<void> _fetchPostDetailAndInteractionStatus() async {

    setState(() {

      _isLoading = true;

      _errorMessage = null;

    });

    try {

      final postResponse = await _postApi.getPostDetail(widget.postId);

      if (postResponse.code == 1000) {

        setState(() {

          _post = postResponse.data;

        });

      } else {

        setState(() {

          _errorMessage = postResponse.msg ?? '获取帖子详情失败';

          _isLoading = false;

          return;

        });

      }



      final likeStatusResponse = await _postApi.getLikeStatus(widget.postId);

      if (likeStatusResponse.code == 1000) {

        setState(() {

          _isLiked = likeStatusResponse.data ?? false;

        });

      } else {

        print('Error fetching like status: ${likeStatusResponse.msg}');

      }



      final collectStatusResponse = await _collectApi.getCollectStatus(widget.postId);

      if (collectStatusResponse.code == 1000) {

        setState(() {

          _isCollected = collectStatusResponse.data ?? false;

        });

      } else {

        print('Error fetching collect status: ${collectStatusResponse.msg}');

      }

    } catch (e) {

      setState(() {

        _errorMessage = '加载帖子详情或互动状态异常: $e';

      });

    } finally {

      setState(() {

        _isLoading = false;

      });

    }

  }



  /// 切换点赞状态

  Future<void> _toggleLike() async {

    setState(() {

      _isLiked = !_isLiked;

    });



    try {

      final response = await _postApi.likePost(widget.postId);

      if (response.code != 1000) {

        setState(() {

          _isLiked = !_isLiked;

        });

        if (mounted) {

          ScaffoldMessenger.of(context).showSnackBar(

            SnackBar(content: Text(response.msg ?? '切换点赞状态失败')),

          );

        }

      } else {

        _fetchPostDetailAndInteractionStatus();

      }

    } catch (e) {

      setState(() {

        _isLiked = !_isLiked;

      });

      if (mounted) {

        ScaffoldMessenger.of(context).showSnackBar(

          SnackBar(content: Text('切换点赞状态异常: $e')),

        );

      }

    }

  }



  /// 切换收藏状态

  Future<void> _toggleCollect() async {

    setState(() {

      _isCollected = !_isCollected;

    });



    try {

      final response = await _collectApi.toggleCollect(widget.postId);

      if (response.code != 1000) {

        setState(() {

          _isCollected = !_isCollected;

        });

        if (mounted) {

          ScaffoldMessenger.of(context).showSnackBar(

            SnackBar(content: Text(response.msg ?? '切换收藏状态失败')),

          );

        }

        return; // Early exit on error

      }

      _fetchPostDetailAndInteractionStatus(); // Refresh status after successful toggle

    } catch (e) {

      setState(() {

        _isCollected = !_isCollected;

      });

      if (mounted) {

        ScaffoldMessenger.of(context).showSnackBar(

          SnackBar(content: Text('切换收藏状态异常: $e')),

        );

      }

    }

  }



// --- 新增：判断内容是否可能是 Markdown 格式的辅助函数 ---

  bool _isContentMarkdown(String content) {

    if (content.isEmpty) return false;



// 检查常见的 Markdown 语法标记

    final markdownIndicators = [

      RegExp(r'^\s*#+\s'), // 标题: #, ##, ###

      RegExp(r'^\s*[-*+]\s'), // 列表: -, *, +

      RegExp(r'^\s*\d+\.\s'), // 有序列表: 1., 2.

      RegExp(r'^\s*>\s'), // 引用: >

      RegExp(r'\*\*[^*-]+\*\*'), // 粗体: **text**

      RegExp(r'__[^_]+__'), // 粗体: __text__

      RegExp(r'\*[^*-]+\*'), // 斜体: *text*

      RegExp(r'_[^_]+_'), // 斜体: _text_

      RegExp(r'\[.+\]\(.+\)'), // 链接: [text](url)

      RegExp(r'!\[.+\]\(.+\)'), // 图片: ![alt](url)

      RegExp(r'`[^`]+`'), // 行内代码: `code`

      RegExp(r'```[\s\S]*?```'), // 代码块: ```code```

      RegExp(r'---|\*\*\*|___'), // 分隔线

    ];



// 只要找到一个强烈的 Markdown 指示符，就认为可能是 Markdown

    for (var regex in markdownIndicators) {

      if (regex.hasMatch(content)) {

        return true;

      }

    }



// 如果内容很长，并且没有明显的 Markdown 标记，可以考虑默认是纯文本

// 或者加入更复杂的逻辑，例如统计有多少行符合某种 Markdown 规则

// 对于此示例，我们采取宽松的判断

    return false;

  }





  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('帖子详情${_post?.title != null ? ': ${_post!.title}' : ''}'),

      ),

      body: _isLoading

          ? const Center(child: CircularProgressIndicator())

          : _errorMessage != null

          ? Center(

        child: Padding(

          padding: const EdgeInsets.all(16.0),

          child: Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: [

              Text(

                '无法加载帖子: $_errorMessage',

                textAlign: TextAlign.center,

                style: const TextStyle(color: Colors.red, fontSize: 16),

              ),

              const SizedBox(height: 16),

              ElevatedButton(

                onPressed: _fetchPostDetailAndInteractionStatus,

                child: const Text('重试'),

              ),

            ],

          ),

        ),

      )

          : _post == null

          ? const Center(child: Text('帖子不存在或已被删除。'))

          : SingleChildScrollView(

        padding: const EdgeInsets.all(16.0),

        child: Column(

          crossAxisAlignment: CrossAxisAlignment.start,

          children: [

// 帖子标题

            Text(

              _post!.title,

              style: Theme.of(context).textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),

            ),

            const SizedBox(height: 8),

// 作者名称

            Text(

              '作者: ${_post!.authorName}',

              style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey[700]),

            ),

// 如果社区名称可用，则显示社区名称

            if (_post!.community?.communityName != null)

              Padding(

                padding: const EdgeInsets.only(top: 4.0),

                child: Text(

                  '社区: ${_post!.community!.communityName}',

                  style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.blueAccent),

                ),

              ),

            const SizedBox(height: 16),

// 帖子内容 - 根据 _isContentMarkdown 判断是否渲染为 Markdown

            if (_isContentMarkdown(_post!.content))

              MarkdownBody(

                data: _post!.content,

                styleSheet: MarkdownStyleSheet(

                  p: Theme.of(context).textTheme.bodyLarge,

                  h1: Theme.of(context).textTheme.headlineLarge,

                  h2: Theme.of(context).textTheme.headlineMedium,

                  h3: Theme.of(context).textTheme.headlineSmall,

                  strong: const TextStyle(fontWeight: FontWeight.bold),

                  em: const TextStyle(fontStyle: FontStyle.italic),

                  code: TextStyle(

                    backgroundColor: Colors.grey[200],

                    fontFamily: 'monospace',

                    fontSize: Theme.of(context).textTheme.bodyMedium?.fontSize,

                  ),

                  blockquote: TextStyle(

                    fontStyle: FontStyle.italic,

                    color: Colors.grey[600],

                    // border: const Border(left: BorderSide(color: Colors.grey, width: 4)),

                  ),

                  a: TextStyle(color: Colors.blue, decoration: TextDecoration.underline),

                  listBullet: Theme.of(context).textTheme.bodyLarge,

                  checkbox: Theme.of(context).textTheme.bodyLarge,

                ),

              )

            else

// 默认使用 Text 组件渲染纯文本

              Text(

                _post!.content,

                style: Theme.of(context).textTheme.bodyLarge,

              ),

            const SizedBox(height: 24),

// 统计信息行（点赞、评论、浏览、收藏）

            Row(

              mainAxisAlignment: MainAxisAlignment.spaceAround,

              children: [

                _buildLikeStatItem(), // 点赞项

                _buildStatItem(Icons.comment_outlined, '评论', _post!.stats?.commentCount ?? 0),

                _buildStatItem(Icons.visibility_outlined, '浏览', _post!.stats?.viewCount ?? 0),

                _buildCollectStatItem(), // 收藏项

              ],

            ),

            const SizedBox(height: 16),

// 发布时间

            if (_post!.createTime != null)

              Align(

                alignment: Alignment.bottomRight,

                child: Text(

                  '发布于: ${formatDateTime(_post!.createTime!)}',

                  style: Theme.of(context).textTheme.bodySmall?.copyWith(color: Colors.grey),

                ),

              ),

            const Divider(height: 32, thickness: 1),

            CommentWidget(postId: widget.postId),

          ],

        ),

      ),

    );

  }



  /// 构建统计项的通用Widget

  Widget _buildStatItem(IconData icon, String label, int count) {

    return Column(

      children: [

        Icon(icon, color: Colors.blueGrey),

        const SizedBox(height: 4),

        Text('$count $label', style: const TextStyle(fontSize: 12)),

      ],

    );

  }



  /// 构建点赞统计项的Widget，包含点赞状态切换逻辑

  Widget _buildLikeStatItem() {

    return GestureDetector(

      onTap: _toggleLike,

      child: Column(

        children: [

          Icon(

            _isLiked ? Icons.thumb_up_alt : Icons.thumb_up_alt_outlined,

            color: _isLiked ? Colors.blue : Colors.blueGrey,

          ),

          const SizedBox(height: 4),

          Text(

            '${_post!.stats?.likeCount} 点赞',

            style: const TextStyle(fontSize: 12),

          ),

        ],

      ),

    );

  }



  /// 构建收藏统计项的Widget，包含收藏状态切换逻辑

  Widget _buildCollectStatItem() {

    return GestureDetector(

      onTap: _toggleCollect,

      child: Column(

        children: [

          Icon(

            _isCollected ? Icons.star : Icons.star_border,

            color: _isCollected ? Colors.amber : Colors.blueGrey,

          ),

          const SizedBox(height: 4),

          Text(

            '${_post!.stats?.collectCount} 收藏',

            style: const TextStyle(fontSize: 12),

          ),

        ],

      ),

    );

  }



  /// 格式化日期时间

  String formatDateTime(DateTime dateTime) {

    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';

  }

}



